package com.simen.hellobytes.encrypt;

import com.simen.hellobytes.HexUtil;
import com.simen.hellobytes.exception.EncryptException;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;

/**
 * @author Created by Simen.
 * @date 创建日期 2018/8/23 10:10
 * @modify 修改者 Simen
 */
public class Md5Util {

    private static final String ALGORITHM_MD5 = "MD5";

    public static String md5HexUTF8(String input) throws UnsupportedEncodingException,EncryptException {
        return md5InputHex(input.getBytes("UTF-8"));
    }

    public static String md5HexGBK(String input) throws UnsupportedEncodingException,EncryptException {
        return md5InputHex(input.getBytes("GBK"));
    }

    public static String md5InputHex(byte[] input) throws EncryptException {
        byte[] bytes = md5Input(input);
        return HexUtil.bytesToHex(bytes);
    }

    public static byte[] md5Input(byte[] input) throws EncryptException {
        return SHAUtil.digest(ALGORITHM_MD5, input);
    }

    public static String md5FileHex(File file) throws EncryptException {
        BigInteger bi = new BigInteger(1, md5File(file));
        return bi.toString(16);
    }

    public static byte[] md5File(File file) throws EncryptException {
        return SHAUtil.digestFile(ALGORITHM_MD5, file);
    }

}
